package com.wn.icloud.advice;

import com.wn.icloud.common.msg.BaseResponse;
import com.wn.icloud.common.msg.ObjectRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 返回值统一封装
 *
 * @author star
 * @date 2019/4/19
 **/
@Slf4j
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Object result;
        if (null == body) {
            result = new BaseResponse();
        } else if (body instanceof BaseResponse) {
            result = body;
        } else {
            result = new ObjectRestResponse<>().data(body);
        }
        return result;
    }
}
